package com.book.system.servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;

    public class BaseServlet extends HttpServlet {
        //反射
        @Override
        public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
            HttpServletResponse response = (HttpServletResponse) res;
            //设置请求的编码格式
            req.setCharacterEncoding("UTF-8");
            //设置响应的编码格式
            response.setContentType("text/html;charset=UTF-8");
            String m = req.getParameter("m");
            try {
                //获取方法对象
                Method method = this.getClass()
                        .getDeclaredMethod
                                (m, HttpServletRequest.class,
                                        HttpServletResponse.class);
                //执行方法
                Object invoke = method.invoke(this, req, response);
                //inn
                if (invoke != null) {
                    response.getWriter().write(JSON.toJSONString(invoke));
                }

            } catch (NoSuchMethodException e) {

                //设置状态码
                response.setStatus(404);
                //返回数据
                response.getWriter().write("{\"msg\":\"请求错误\"}");
            } catch (Exception e) {
                e.printStackTrace();
                response.setStatus(500);
                response.getWriter().write("{\"msg\":\"服务器繁忙,请稍后再试！\"}");
            }
        }

        /**
         * 获取请求体数据
         *
         * @param request 请求对象
         * @return string
         */
        public String getRequestBody(HttpServletRequest request) {
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = null;
            try {
                //读取请求对象中请求体数据
                reader = request.getReader();
                //创建缓冲(缓存)对象
                String line;
                //读取流中的数据
                while ((line = reader.readLine()) != null) {
                    //追加(添加)到返回结果对象中
                    builder.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    //关闭流对象
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return builder.toString();
        }

    }
